package com.zhijian.warehouse.manage.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public FileUtil() {
    }

    public static File createFile(String filePath, String fileName, boolean covered) throws IOException {
        File path = new File(filePath);
        if (!path.exists() || !path.isDirectory()) {
            path.mkdirs();
        }
        if (!filePath.endsWith("/")) {
            filePath = filePath + "/";
        }
        File file = new File(filePath + fileName);
        if (covered && file.exists() && file.isFile()) {
            file.delete();
        }
        if (!file.exists() || !file.isFile()) {
            file.createNewFile();
        }
        return file;
    }

    public static File saveLocalFile(String filePath, String fileName, MultipartFile multipartFile, boolean covered) {
        try {

            File localFile = createFile(filePath, fileName, covered);
            //TODO 如果因环境问题找不到指定路劲 使用下面输入流保存文件
            multipartFile.transferTo(localFile);

            // 使用输入流保存文件
           /* try (InputStream inputStream = multipartFile.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(localFile)) {
                byte[] buffer = new byte[2048];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }*/
            return localFile;
        } catch (Exception var5) {
            Exception ex = var5;
            logger.error("{}| saveLocalFile exception", fileName, ex);
            return null;
        }
    }
}
